<?php

namespace app\service;

//用户土地解锁服务
use app\model\UserPosition;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class UserPositionService extends BaseService
{

    public function initPosition($user_id)
    {
        $user_position = new UserPosition();
        $user_position->user_id = $user_id;
        $position = json_encode(['152,150', '162,532']);
        $user_position->position = $position;
        $user_position->save();
    }

    /**
     * 获取用户土地列表
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function list($user_id): array
    {
        $user_position = UserPosition::where('user_id', $user_id)->find();
        $user_position->position = json_decode($user_position->position, true);
        return $this->returnSuccess($user_position);
    }


    /**
     * 解锁土地
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function unlock_position($user_id, $position_x, $position_y): array
    {

        // $position_x,$position_y不能是null
        if ($position_x == null || $position_y == null) {
            return $this->returnFail('position_x和position_y不能为空');
        }

        $user_position = UserPosition::where('user_id', $user_id)->find();
        $position = json_decode($user_position->position, true);
        $position_str = $position_x.','.$position_y;

        //是否重复
        if (in_array($position_str, $position)) {
            return $this->returnFail('该土地已解锁');
        }
        $position[] = $position_str;
        $user_position->position = json_encode($position);
        $user_position->save();
        $user_position->position = json_decode($user_position->position, true);

        return $this->returnSuccess($user_position);
    }


}